<!-- 点击分配角色的对话框 -->
<template>
  <el-dialog
    v-model="visible"
    title="分配角色"
    :before-close="cancel"
    width="20%"
  >
    <el-form :model="form">
      <el-form-item>
        <el-select multiple v-model="form.selectRoleIds">
          <el-option
            v-for="role in roleLists"
            :key="role.id"
            :label="role.name"
            :value="role.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { umsRole, umsAdmin } from "../../../../request/http";
const props = withDefaults(
  defineProps<{
    visible: boolean;
    adminId: number;
  }>(),
  {
    visible: false,
  }
);

const emit = defineEmits<{
  (event: "close"): void;
}>();

const roleLists = ref([] as umsRole.RoleDataObj[]);

// 获取所有用户角色
async function fetchRolesData() {
  const roleListsRes = await umsRole.getRoleListAll();
  if (roleListsRes.code === 200) {
    roleLists.value = roleListsRes.data;
  }
}
fetchRolesData();
// 获取当前用户角色列表
async function getRolesListByAdminId() {
  const adminRole = await umsAdmin.getAdminRoleById(props.adminId);
  if (adminRole.code === 200) {
    form.selectRoleIds = adminRole.data.map((item) => item.id);
  }
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      getRolesListByAdminId();
    }
  }
);

const form = reactive({
  selectRoleIds: [] as number[],
});

function cancel() {
  emit("close");
}

async function submit() {
  const updateAdminRoleRes = await umsAdmin.updateAdminRole({
    adminId: props.adminId,
    roleIds: form.selectRoleIds.join(","),
  });
  if (updateAdminRoleRes.code === 200) {
    cancel();
    // 提示
  }
}

// From Data的形式可以这样做
async function submit1() {
  const updateAdminRoleRes = await umsAdmin.updateAdminRole1({
    adminId: props.adminId,
    roleIds: form.selectRoleIds,
  });
  if (updateAdminRoleRes.code === 200) {
    cancel();
    // 提示
  }
}
</script>
<style lang="less" scoped></style>
